import random

from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from urlTest.models import Grade, Student


def students(request):
    return HttpResponse('Get students successfully!')


def student(request,s_id):
    print (s_id)

    print(type(s_id))

    return HttpResponse('Get student %s successfully!' % s_id)


def grades(request):

    grade_list = Grade.objects.all()
    print(locals())
    #locals()，内置函数，将局部变量使用字典的方式进行打包，key是变量名，value是变量的数据
    return render(request,'grade_list.html',context=locals())


def get_students(request,g_id):

    student_list = Student.objects.filter(s_grade_id=g_id)

    return render(request,'grade_student.html',context=locals())


def get_time(request, hour, minutes, secend):
    return HttpResponse("Time %s : %s : %s" % (hour,minutes,secend))

def get_date(request, year, month, day):
    return HttpResponse("Date %s - %s - %s" % (year,month,day))


def learn(request):
    return HttpResponse("你是爱学习的好孩子")

def have_request(request):
    print(request.path)

    print(request.method)

    print(request.GET)

    #获取GET请求参数
    #请求体：http://127.0.0.1:8000/urltest/have_request/?hobby=eating&hobby=playing

    hobby = request.GET.get('hobby')

    hobbies = request.GET.getlist('hobby')

    print(request.POST)
    print(hobbies)

    #请求者的源信息
    print(request.META)

    for key in request.META:
        print(key,request.META.get(key))

    print("remote ip : %s " % request.META.get("REMOTE_ADDR"))

    return HttpResponse("Request success")


def create_student(request):
    return render(request,'student_post.html')


def do_create_student(request):

    print(request.POST)

    username = request.POST.get('username')

    return HttpResponse(username)


def do_response(request):

    response = HttpResponse()

    response.write("获取返回测试页面！")

    #记得经常刷新内存缓存池
    response.flush()

    return response


def do_redirect(request):

    url = reverse('urlsnamespace:do_response')
    #50%概率进行重定向
    if random.randrange(10) > 5:
        # return HttpResponseRedirect(url)
        return redirect(url)

    return HttpResponse("原有地址返回成功！")


def do_json(request):

    data = {
        "status" : 200,
        "msg" : "ok",
    }

    return JsonResponse(data=data)


def logout(request):

    response = redirect(reverse("urlsnamespace:main"))

    response.delete_cookie("name")

    return response

def setcookie(request):

    response = HttpResponse("设置Cookie")
    #设置cookie内容
    response.set_cookie('username','extraxue')

    return response


def getcookie(request):
    #获取Cookie的值
    username = request.COOKIES.get("username")

    return HttpResponse(username)


def login(request):

    return render(request,'login.html')


def dologin(request):

    # get的是表单中的name：<span>用户名：</span><input type="text" placeholder="请输入用户名" name="uname">
    uname = request.POST.get('uname')

    response = HttpResponseRedirect(reverse('urlsnamespace:main'))

    # example 1 ：
    # response.set_cookie('name',uname,max_age=60)
    # 还可以设置过期时间等
    # response.set_cookie(key, value[, max_age = None, expires = None)]
    # max_age 整数，单位秒，就算关浏览器了也可以，因为cookie是以文件形式保存在客户端上的
    # expire 指定时间datetime或timedelta或具体的时间

    # example 2:
    # 加盐（加签名）存储cookie，盐值：Extra
    response.set_signed_cookie('name',uname,salt="Extra")

    return response


def main(request):

    # example 1 :普通获取
    # uname = request.COOKIES.get('name')

    # example 2 : 加盐获取，用什么盐进行签名的 就是什么盐去解，盐值：Extra
    try:

        uname = request.get_signed_cookie('name',salt="Extra")
        # 如果有用户名就限制登录信息 没有就返回到登录界面
        if uname:
            return render(request, 'to_mine.html', context=locals())
    except Exception as e:
        print("获取Cookie失败")

    return redirect(reverse('urlsnamespace:login'))
